
from pyramid.httpexceptions import HTTPFound
from pyramid.security import remember
from pyramid.security import forget

from scp.security import USERS


from scp.modelo.models import DBSession
from scp.modelo.Usuario import Usuario

def login(request):
	
	print request

	print '\nholaaaaaaaaaaaaaaa desde controller!!!!!\n'

	login_url = request.route_url('login')

	print 'despues de login_url'

	referrer = request.url
	print 'despuelogin_urls de request.url'

	if referrer == login_url:
		referrer = '/' # never use the login form itself as came_from
	came_from = request.params.get('came_from', referrer)

	print 'despues del came_from'    

	message = ''
	login = ''
	password = ''

		
	print 'entre en el if!!!!!!'

	if 'form.submitted' in request.params:
		login = request.params['login']
		password = request.params['password']
		

		if login != None and login != "" and password != None and password != "": 

			session = DBSession()
			
			usuario = session.query(Usuario).filter_by(username=login).first()
			
			
			if usuario != None:
			
				if usuario.password == password:
					print "esto trajimos de la BD-->" + usuario.username
					
					headers = remember(request, login) 
					return HTTPFound(location = came_from,
									 headers = headers)
				else:
					message = 'Contrasenha incorrecta'
					password = ""
					
			else:
				message = 'Usuario ingresado no existe'
				login = ""
				password = ""
		else:
			message = "Se debe ingresar Nombre de Usuario y Contrasenha!!"
			login = ""
			password = ""

	diccionario = dict(
		message = message,
		url = request.application_url + '/login',
		came_from = came_from,
		login = login,
		password = password,
		)

	print diccionario

	return diccionario

	#return HTTPFound(location = came_from,
							 #headers = headers)

    
def logout(request):
    headers = forget(request)
    return HTTPFound(location = request.route_url('view_wiki'),
                     headers = headers)
